package com.android.lyricshow.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.android.lyricshow.bean.SongBean;
import com.android.lyricshow.service.LyricParser;
import com.android.lyricshow.service.Sentence;

public class LrcView extends TextView{
	
	private Paint mPaint;
	private Paint mPaintCur;
	
	private float mX;
	private float middleY;
	private int mY;
	
	private int DY			= 50;
	
	private float mTextSize;
	
	private LyricParser mLyric;
	
	private int mCurIndex	= -1;
	
	private List<Sentence> mList = new ArrayList<Sentence>();

	private boolean mIsInit	= false;
	
	public LrcView(Context context) {
		super(context);
		init();
	}

	public LrcView(Context context, AttributeSet attr) {
		super(context, attr);
		init();
	}

	public LrcView(Context context, AttributeSet attr, int i) {
		super(context, attr, i);
		init();
	}
	
	private void init() {
		setFocusable(true);
		
		mTextSize = this.getTextSize();
		DY = (int)mTextSize + 18;
		
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setTextSize(mTextSize);
		mPaint.setColor(Color.WHITE);
		
		mPaintCur = new Paint();
		mPaintCur.setAntiAlias(true);
		mPaintCur.setTextSize(mTextSize);
		mPaintCur.setColor(Color.MAGENTA);
	}
	
	public void init(String path, SongBean sbean){
		synchronized (mList){
			mLyric	= new LyricParser(path, sbean);
			mList 	= mLyric.getList();
			
			mIsInit = true;
		}
	}
	
	protected void onDraw(Canvas canvas) {
		
		super.onDraw(canvas);
		
		if (mCurIndex == -1 || !mIsInit){
			return;
		}

		Paint normal = mPaint;
		Paint current= mPaintCur;

		normal.setTextAlign(Paint.Align.CENTER);
		current.setTextAlign(Paint.Align.CENTER);
		
		float tempY = middleY;
		for (int i = mCurIndex - 1; i >= 0; i--) {
			tempY = tempY - DY;
			if (tempY < 0) {
				break;
			}
			
			canvas.drawText(mList.get(i).getContent(), mX, tempY, normal);
		}
		
		canvas.drawText(mList.get(mCurIndex).getContent(), mX, middleY, current);
		tempY = middleY;
		
		int count = mList.size();
		for (int i = mCurIndex + 1; i < count; i++) {
			tempY = tempY + DY;
			if (tempY > mY) {
				break;
			}
			canvas.drawText(mList.get(i).getContent(), mX, tempY, normal);
		}
	}
	
	protected void onSizeChanged(int w, int h, int ow, int oh) {
		super.onSizeChanged(w, h, ow, oh);
		mX = w * 0.5f;
		mY = h;
		middleY = h * 0.5f;
	}
	
	public void clear(){
		
		mIsInit		= false;
		mCurIndex	= -1;
		
		this.invalidate();
	}
	
	public void updateIndex(long time) {
		synchronized (mList) {
			if(!mIsInit || mLyric == null){
				return;
			}
			
			if ((mCurIndex = mLyric.getNowSentenceIndex(time)) != -1){
				this.invalidate();
			}
		}
	}
}
